package cn.cdzdjd.service.impl;

import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;

import cn.cdzdjd.constant.BrowserConstant;
import cn.cdzdjd.dao.DictMapper;
import cn.cdzdjd.entity.Dict;
import cn.cdzdjd.exception.ErrorCode;
import cn.cdzdjd.exception.RenException;
import cn.cdzdjd.service.WeiBoService;
import cn.cdzdjd.util.UrlUtil;
import cn.cdzdjd.vo.VideoInfoVO;
import cn.hutool.core.util.RandomUtil;
import kong.unirest.HttpResponse;
import kong.unirest.Unirest;
import lombok.extern.slf4j.Slf4j;

@Service
@Slf4j
public class WeiBoServiceImpl implements WeiBoService {
	String baseUrl = "https://weibo.com/ajax/statuses/show?id={id}&locale=zh-CN";
	String videoBaseUrl = "https://h5.video.weibo.com/api/component?page=/show/{fid}";
	// https://video.weibo.com/show?fid=1034:5003172616536117
	@Resource
	private DictMapper dictMapper;

	@Override
	public VideoInfoVO getVideoInfo(String url) {
		try {
			URL u = new URL(url);
			Map<String, String> params = UrlUtil.convertUrlParamsToMap(u);
			LambdaQueryWrapper<Dict> queryWrapper = new LambdaQueryWrapper<>();
			queryWrapper.eq(Dict::getCode, "weibo_cookie");
			List<Dict> list = dictMapper.selectList(queryWrapper);
			int i = RandomUtil.randomInt(0, list.size());
			// 微博视频
			if (params.get("fid") != null) {
				HttpResponse<String> response = Unirest.post(videoBaseUrl.replace("{fid}", params.get("fid")))
						.header("content-type", "application/x-www-form-urlencoded")
						.header("cookie", list.get(i).getContent()).header("origin", "https://" + u.getHost())
						.header("referer", "https://" + u.getHost() + "/show/" + params.get("fid"))
						.header("user-agent", BrowserConstant.USER_AGENT_PC)
						.field("data", "{\"Component_Play_Playinfo\":{\"oid\":\"" + params.get("fid") + "\"}}")
						.asString();

				JSONObject json = new JSONObject(response.getBody());
				JSONObject playInfo = json.getJSONObject("data").getJSONObject("Component_Play_Playinfo");
				String title = playInfo.getString("title");
				System.out.println(title);
				String cover_img = playInfo.getString("cover_image");
				List<String> posterList = new ArrayList<>();
				posterList.add("https:" + cover_img);
				List<String> videoList = new ArrayList<>();
				JSONObject urls = playInfo.getJSONObject("urls");
				Iterator<String> iterator = urls.keys();
				while (iterator.hasNext()) {
					String key = (String) iterator.next();
					String value = urls.getString(key);
					videoList.add("https:" + value);
				}
				return new VideoInfoVO(videoList, posterList, title, null);
			} else {
				String path = UrlUtil.getPath(url);
				int index = StringUtils.lastOrdinalIndexOf(path, "/", 1);
				String id = StringUtils.substring(path, index + 1);
				String url_final = StringUtils.replace(baseUrl, "{id}", id);
				HttpResponse<String> response = Unirest.get(url_final).header("Cookie", list.get(i).getContent())
						.header("User-Agent", BrowserConstant.USER_AGENT_PC).asString();
				String jsonStr = response.getBody();
				JSONObject json = new JSONObject(jsonStr);
				// 标题
				String title = json.getString("text_raw");
				// 纯图
				if (json.has("pic_infos")) {
					log.info("纯图");
					JSONArray picIds = json.getJSONArray("pic_ids");
					JSONObject picInfos = json.getJSONObject("pic_infos");
					List<String> posterList = new ArrayList<>();
					for (int j = 0; j < picIds.length(); j++) {
						String pic_key = picIds.getString(j);
						JSONObject picInfo = picInfos.getJSONObject(pic_key);
						String picUrl = picInfo.getJSONObject("original").getString("url");
						posterList.add(UrlUtil.setHttps(picUrl));
					}
					return new VideoInfoVO(null, posterList, title, null);
				}
				// 视频图片混合
				if (json.has("mix_media_info")) {
					log.info("混合");
					JSONObject mix_media_info = json.getJSONObject("mix_media_info");
					JSONArray items = mix_media_info.getJSONArray("items");
					List<String> posterList = new ArrayList<>();
					List<String> videoList = new ArrayList<>();
					for (int j = 0; j < items.length(); j++) {
						JSONObject item = items.getJSONObject(j);
						if (item.getString("type").equals("pic")) {
							String picUrl = item.getJSONObject("data").getJSONObject("original").getString("url");
							posterList.add(UrlUtil.setHttps(picUrl));
						}
						if (item.getString("type").equals("video")) {
							String videoUrl = item.getJSONObject("data").getJSONObject("media_info")
									.getString("stream_url");
							String posterUrl = item.getJSONObject("data").getString("page_pic");
							videoList.add(UrlUtil.setHttps(videoUrl));
							posterList.add(UrlUtil.setHttps(posterUrl));
						}
					}
					return new VideoInfoVO(videoList, posterList, title, null);
				}
				// 纯视频
				if (json.has("page_info")) {
					log.info("单个纯视频");
					JSONObject pageinfo = json.getJSONObject("page_info");
					JSONObject media_info = pageinfo.getJSONObject("media_info");
					String videoUrl = media_info.getString("stream_url_hd");
					String posterUrl = pageinfo.getString("page_pic");
					List<String> posterList = new ArrayList<>();
					posterList.add(UrlUtil.setHttps(posterUrl));
					List<String> videoList = new ArrayList<>();
					videoList.add(UrlUtil.setHttps(videoUrl));
					return new VideoInfoVO(videoList, posterList, title, null);
				}
			}
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		throw new RenException(ErrorCode.PARSE_ERROR);
	}

}
